<template>
  <base-breadcrumb :title="$route.meta.title" :breadcrumb="!isAudit">
    <!-- 试验计划详情 -->
    <div id="base-breadcrumb" style="position: relative">
      <!-- 项目信息 -->
      <a-card :bordered="false">
        <title-name title="项目信息"></title-name>
        <a-row style="padding: 0 32px">
          <a-col :span="24">
            <a-row class="experimentPlan_box" :gutter="12">
              <a-col :span="3" class="experimentPlan_name">所属单位：</a-col>
              <a-col :span="21" class="experimentPlan_desc">
                {{(project.branchCompanyName || branchCompanyName) + '/' + (project.projectName || projectName)}}</a-col>
<!--              <a-col :span="3" class="experimentPlan_name">项目名称：</a-col>-->

<!--              <a-col :span="10" class="experimentPlan_desc">{{ project.projectName || projectName || '暂无' }}</a-col>-->
            </a-row>
          </a-col>
          <a-col :span="24">
            <a-row class="experimentPlan_box" :gutter="12">
              <a-col :span="3" class="experimentPlan_name">项目基本情况：</a-col>
              <a-col :span="21" class="experimentPlan_desc">{{
                project.projectBasicSituation || projectBasicSituation || '暂无'
              }}</a-col>
            </a-row>
          </a-col>
        </a-row>
      </a-card>
      <a-card :bordered="false" style="margin-bottom: 50px" v-if="editModel == 0">
        <title-name title="试验计划" />
          <service-export-mould
            class="ml12"
            :isButton="true"
            :serviceiUrl="qualityApiUrl"
            buttonType="default"
            :url="'/quality/experiment-plan/excels/' + id"
            buttonText="全部导出"
          ></service-export-mould>
          <div style="margin: 20px; margin-right: 0;" v-for="(val, key) in details" :key="key">
            <title-name :title="key"></title-name>
            <!-- 表格 -->
            <a-table bordered :data-source="val" :columns="columns" :rowKey="record => record.id" size="default" style="width: 100%; overflow-x: auto;" :pagination="false">
              <span slot="actions" slot-scope="text, record, $index">
                <template>
                  <a @click="handleManage(2, record)">详情</a>
                  <a-divider v-if="!!+record.numberOfTests" type="vertical"></a-divider>
                  <a v-if="!!+record.numberOfTests" @click="openExperimentRecord(record)">查看试验记录</a>
                </template>
              </span>
            </a-table>
          </div>
      </a-card>
      <!-- 表格 -->
      <a-card :bordered="false" style="margin-bottom: 50px" v-else>
        <title-name title="试验计划"></title-name>
        <a-button v-if="isEdit" icon="plus" class="mb12" type="primary" :loading="addLoading" @click="handleManage(0)"
          >添加行</a-button
        >
        <div>
          <a-table bordered :data-source="dataSource" :columns="columns" :rowKey="record => record.id" size="default" style="width: 100%; overflow-x: auto;" :pagination="false">
            <span slot="actions" slot-scope="text, record, $index">
              <template>
                <a @click="handleManage(2, record)">详情</a>
                <a-divider v-if="isShowEdit(record)" type="vertical"></a-divider>
                <a v-if="isShowEdit(record)" @click="handleManage(1, record)">修改</a>
                <a-divider v-if="isShowEdit(record)" type="vertical"></a-divider>
                <a v-if="isShowEdit(record)" class="del_btn" @click="handleDel($index)">删除</a>
              </template>
            </span>
          </a-table>
        </div>
      </a-card>
      <!-- 页脚操作栏 -->
      <div
        class="btn_box page-btn-right-top"
      >
      <BasePrintButton
        :before-print-fn="beforePrintFn"
        class="button_right"
      />
        <a-button
          :disabled="loading[0] || loading[1]"
          type="danger"
          v-if="editModel == 1 && status != 4 && status != 3 && !isFromAudit"
          class="button_right"
          @click="handleDeleteALL"
          >删除草稿</a-button
        >
        <a-button
          :loading="loading[0]"
          :disabled="loading[1]"
          type="primary"
          v-if="editModel == 1 && (status === '0' || status === '3' || status === '4') && !isFromAudit"
          class="button_right"
          @click="beforeSubmit(0)"
          >{{ status === '3' ? '保存' : '保存草稿' }}</a-button
        >
        <a-button
          :loading="loading[1]"
          :disabled="loading[0]"
          v-if="isEdit"
          type="primary"
          class="button_right"
          @click="beforeSubmit('1')"
          >提交</a-button
        >
        <a-button v-if="checkVisibleInDetail && !isConsultation && isFromAudit" type="primary" @click="handleActiveClose">关闭</a-button>
      </div>
    </div>
    <!-- 实施计划表单弹窗 -->
    <dialog-experiment-plan
      width="800px"
      :visible.sync="visible"
      :editModel="editModelTwo"
      :form="forms"
      :headerTitle="headerTitle"
      @confirm="submitForm"
    ></dialog-experiment-plan>
    <!-- 查看试验记录弹窗 -->
    <dialog-experiment-record
      width="800px"
      :visible.sync="visibleRecord"
      :form="formsRecord"
    ></dialog-experiment-record>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { qualityApiUrl } from '@/api/config.js'
import { experimentPlan, print } from '@/api/quality/quality' // api
import dialogExperimentPlan from '@/views/quality/experiment/experimentPlan/dialogExperimentPlan' // 表单弹窗
import dialogExperimentRecord from '@/views/quality/experiment/experimentPlan/dialogExperimentRecord' // 表单弹窗

import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BasePrintButton from '@/components/BasePrintButton' // 打印按钮
import ServiceExportMould from '@/components/ServiceExportMould'
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    dialogExperimentPlan,
    dialogExperimentRecord,
    BasePrintButton,
    ServiceExportMould
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    // 是否可编辑
    isEdit() {
      if (this.isFromAudit) {
        return false
      } else {
        return (this.editModel == 1 && (this.status == 0 || this.status == 3 || this.status == 4)) || this.editModel == 3
      }
    },
    // 弹窗动态标题
    headerTitle() {
      return ['添加试验计划', '编辑试验计划', '查看试验计划'][this.editModelTwo]
    },
    // 试验计划表头
    columns() {
      let columns = [
        {
          title: '试验项目编号',
          width: 150,
          dataIndex: 'number'
        },
        {
          title: '试验项目',
          ellipsis: true,
          dataIndex: 'experimentProject',
          customRender(text, record, index) {
            if (record.experimentProject && record.experimentProject.indexOf('其他') > -1) {
              return record.experimentProject + (record.otherExperimentProjectName ? '-'+ record.otherExperimentProjectName : '')
            } else {
              return record.experimentProject
            }
            
          },
        },
        {
          title: '规格',
          ellipsis: true,
          dataIndex: 'specification'
        },
        {
          title: '使用部位',
          ellipsis: true,
          dataIndex: 'applicationPlace'
        },
        {
          title: '试验依据',
          ellipsis: true,
          dataIndex: 'experimentBasis'
        },
        {
          title: '工艺检验',
          ellipsis: true,
          dataIndex: 'processInspection'
        },
        {
          title: '现场检验',
          ellipsis: true,
          dataIndex: 'siteInspection'
        },
        {
          title: '代表批量',
          ellipsis: true,
          dataIndex: 'representativeBatch'
        },
        {
          title: '试验内容',
          ellipsis: true,
          dataIndex: 'experimentContent'
        },
        {
          title: '试验次数',
          ellipsis: true,
          dataIndex: 'numberOfTests'
        },
        {
          title: '责任人',
          ellipsis: true,
          dataIndex: 'dutyPeople'
        }
      ]
      if (this.editModel == 0) {
        columns.push(
          {
            title: '状态',
            dataIndex: 'status',
            customRender(text) {
              return text !== 1 ? '未完成' : '已完成'
            }
          },
          {
            title: '操作',
            dataIndex: 'actions',
            width: '180px',
            fixed: 'right',
            scopedSlots: { customRender: 'actions' }
          }
        )
      } else {
        columns.push({
          title: '操作',
          dataIndex: 'actions',
          width: '180px',
          fixed: 'right',
          scopedSlots: { customRender: 'actions' }
        })
      }
      return columns
    }
  },
  data() {
    return {
      visibleRecord: false,
      formsRecord: {},
      qualityApiUrl,
      dataSource: [],
      loading: { 0: false, 1: false },
      id: '',
      projectBasicSituation: '',
      branchCompanyName: '',
      projectName: '',
      printId: '',
      visible: false,
      editModelTwo: 0,
      status: '', // 审批状态
      forms: {},
      addLoading: false, // 添加编号加载loading
      project: {},
      details: {},
      isFromAudit: false, // 是否来自审批
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
 async mounted() {
    this.form = this.$route.query
    this.printId = this.form.projectId
    this.getDetail()
    this.isFromAudit = !!this.$route.query.businessId
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('quality_experiment_plan')
  },
  methods: {
    isShowEdit(record) {
      const editModel = this.editModel
      if (this.isFromAudit) {
        return false
      } else {
        if (editModel == 0) {
          return false
        } else {
          if (Object.prototype.hasOwnProperty.call(record, 'numberOfTests')) {
            if (+record.numberOfTests < 1) {
              return true
            } else {
              return false
            }
          } else {
            return true
          }
        }
      }
    },
    // 打印
    beforePrintFn() {
      // 批量打印 templateCode: CSCEC8XN-EQ-B30207，id: 措施计划id
        return print.generateBatchDoc({id:this.id, templateCode: 'CSCEC8XN-EQ-B30207'}).then((res) => {
          return res.data.content
        })
    },
    getDetail() {
      let args = {}
        let name = this.historyId ? 'getHisDetail' : 'getDetail'
        if (this.id) {
          args.id = this.id
        } else {
          args.projectId = this.projectId
        }
        args.isView = this.editModel == 0 ? 1 : 0
        this.historyId && (args.historyId = this.historyId)
        return experimentPlan[name](args).then((res) => {
          if (res.data) {
            this.project = res.data.projectInfo
            this.details = res.data.mapExperimentPlan || {}
            if (res.data.experimentPlan) {
              this.dataSource = res.data.experimentPlan.map((item, index) => {
                item.experimentProjectInfo = {
                  key: item.experimentProjectId || '',
                  label: item.experimentProject || ''
                }
                item.dutyPeopleInfo = {
                  key: item.dutyPeopleId || '',
                  label: item.dutyPeople || ''
                }
                item.siteInspectionInfo = {
                  key: item.siteInspectionId || '',
                  label: item.siteInspection || ''
                }
                item.key = index
                return item
              }) // 列表对象
            }
          }
        })
    },
    // 提交表单
    submitForm(e) {
      let that = this
      e.experimentProjectId = e.experimentProjectInfo.key
      e.experimentProject = e.experimentProjectInfo.label
      e.dutyPeopleId = e.dutyPeopleInfo.key
      e.dutyPeople = e.dutyPeopleInfo.label
      e.siteInspection = e.siteInspectionInfo.label
      e.siteInspectionId = e.siteInspectionInfo.key
      e.key = this.dataSource.length
      if (!that.editModelTwo) {
        if (this.dataSource.length > 0) {
          this.dataSource.unshift(e)
        } else {
          this.dataSource = [e]
        }
        that.$message.success('添加成功，请保存草稿或提交！')
      } else {
        Object.assign(that.forms, e)
        that.$message.success('编辑成功，请保存草稿或提交！')
      }
      // 关闭弹窗
      that.visible = false
    },
    // 搜索
    search(value) {
      this.$refs.table.refresh(true)
    },
    handleDel(e) {
      let that = this
      if (this.dataSource.length == 1) {
        that.$message.warning('不能删除最后一条')
        return
      }
      that.$confirm({
        title: '温馨提示',
        content: '确认删除？',
        okText: '确认',
        cancelText: '关闭',
        onOk() {
          that.dataSource.splice(e, 1)
          that.$message.success('删除成功，请保存草稿或提交！')
        }
      })
    },
    openExperimentRecord(record) {
      this.visibleRecord = true
      this.formsRecord = {
        id: this.id,
        detailId: record.id
      }
    },
    // 表格操作
    handleManage(type, record) {
      this.editModelTwo = type
      if (type) {
        if (!record.experimentProjectInfo) {
          record.experimentProjectInfo = {
            key: record.experimentProjectId || '',
            label: record.experimentProject || ''
          }
        }
        if (!record.dutyPeopleInfo) {
          record.dutyPeopleInfo = {
            key: record.dutyPeopleId || '',
            label: record.dutyPeople || ''
          }
        }
        if (!record.siteInspectionInfo) {
          record.siteInspectionInfo = {
            key: record.siteInspectionId || '',
            label: record.siteInspection || ''
          }
        }
      }
           
      // 传递行参数
      this.forms = type ? record : {}
      this.forms.branchCompanyId = this.project.branchCompanyId
      this.forms.projectId = this.project.projectId
      // 若是添加操作则请求试验编号
      if (type === 0) {
        if (!this.project.projectId) {
          this.$message.error('详情项目不存在')
          return false
        }
        this.addLoading = true
        experimentPlan
          .getNumber(this.project.projectId)
          .then((res) => {
            this.addLoading = false
            if (res.data.code === 200) {
              this.forms.number = res.data.message
              this.visible = true
            }
          })
          .catch(() => {
            this.addLoading = false
          })
      } else {
        this.visible = true
      }
    },
    // 删除草稿
    handleDeleteALL() {
      let that = this
      that.$confirm({
        title: '温馨提示',
        content: '确认删除草稿？',
        okText: '确认',
        cancelText: '关闭',
        onOk() {
          return experimentPlan.remove({ id: that.id }).then((res) => {
            that.$message.success('删除成功！')
            that.$multiTab.close()
          })
          // .catch((res) => {
          //   that.$message.warning('删除失败！')
          // })
        }
      })
    },
    // 校验表单
    beforeSubmit(status) {
      let that = this
      if (this.dataSource.length < 1 && status !== 0) {
        that.$message.warning('实施计划列表不能为空')
        return
      }
      if (status !== 0) {
        this.submitApprovalConfirm(this.processConfig, (flag)=>{
          if(!flag) {
            return
          }
          that.handleSubmit(status)
        })
      } else {
        that.handleSubmit(status)
      }
    },
    // 提交表单
    handleSubmit(status) {
      let that = this
      that.setProcessConfig = null;
      let name = ['update', 'update', 'adjustment'][that.editModel - 1] // 动态取得api请求方法
      let form = {
        id: that.id,
        experimentPlan: this.dataSource,
        projectInfo: that.form,
        statusCode: that.status == 3 && status == 0 ? that.status : status
      }
      // 加载框
      that.loading[status] = true
      return experimentPlan[name](form)
        .then((res) => {
          that.loading[status] = false
          if (res.code === 200 || res.data.code === 200) {
            // 取消加载框
            that.$message.success(['保存', '提交'][status] + '成功！')
            if(status*1===1) {
          //提交时，返回id
              that.businessId = res.data.id;
              that.setProcessConfig = this.processConfig;
              return
          }else{
            that.$multiTab.close()
            }
          }
        })
        .catch((res) => {
          // that.$message.warning(['保存', '提交'][status] + '失败！')
          // 取消加载框
          that.loading[status] = false
        })
    }
  }
}
</script>
<style lang="less" scoped>
.experimentPlan_box {
  padding: 12px 0;
  .experimentPlan_name {
    text-align: right;
    color: #989898;
  }
  .experimentPlan_desc {
    color: #666666;
  }
}
</style>
